/**  
 * All rights Reserved, Designed By Android_Robot   
 * @Title:  LeaderViewReportActivity.java   
 * @Package com.jiyi.activity.leader   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: HYM     
 * @date:   2017-10-31 下午1:55:47   
 * @version V1.0     
 */
package com.jiyi.activity.leader;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jiyi.activity.new_maintenance.repair.MaintenanceDeclareRepairTableActivity;
import com.jiyi.adapter.RepairItemAdapter;
import com.jiyi.bean.maintenance.RepairItemBean;
import com.jiyi.bean.maintenance.RepairItemParent;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.easemob.util.UserHelp;
import com.jiyi.event.CheckUploadEvent;
import com.jiyi.event.OwnerCheckEvent;
import com.jiyi.event.RepairTaskListEvent;
import com.jiyi.inteface.ConfirmPopInterface;
import com.jiyi.inteface.WebApi;
import com.jiyi.view.ConfirmPopView;
import com.swift.base.ActivityBase;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppBase;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @ClassName: LeaderViewReportActivity
 * @Description:TODO(主管端-查看报告)
 * @author: HYM
 * @date: 2017-10-31 下午1:55:47
 * 
 */
public class LeaderViewReportActivity extends ActivityBase implements ConfirmPopInterface{

	/* 头部 */
	@BindView(R.id.tvBack)
	TextView tvBack;
	@BindView(R.id.tvTitle)
	TextView tvTitle;
	@BindView(R.id.tvSearch)
	TextView tvSearch;

	RepairItemAdapter mRepairItemAdapter;

	ArrayList<RepairItemParent> mRepairItemParents = new ArrayList<RepairItemParent>();

	@BindView(R.id.mainList)
	ExpandableListView mainList;

	@BindView(R.id.tvUpload)
	TextView tvUpload;

	// 显示的类别 1 编辑 2 查看 3 有编辑有查看 4 新增 5 审核
	private int type;
	// 维修的表头
	String bid,ownerId;

	Dialog dialog;
	//添加临检报表
	private final int ADD = 1;
	
	ConfirmPopView mConfirmPopView;
	
	List<RepairItemBean> updateCopy = new ArrayList<RepairItemBean>();
	
	int position;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_leader_view_report);
		ButterKnife.bind(this);
		init();
	}

	@Override
	protected void onDestroy() {
		hideDialog(dialog);
		EventBus.getDefault().unregister(this);
		super.onDestroy();
	}
	
	@Subscribe
	public void onCheckUploadEvent(CheckUploadEvent checkUploadEvent) {
		checkPost();
	}

	private void init() {
		getIntentData();
		setTop();
		setAdapter();
		getData();
		if (type == 4 || type == 5) {
			checkPost();
		}
		mConfirmPopView = new ConfirmPopView(this, this, "为方便当前操作便捷，需要跳过业主审核直接进入后续操作吗？跳过后将默认业主已同意继续该任务涉及到的维修金额，维保人员可立马执行该任务", "需要业主审核", "跳过业主审核");
		EventBus.getDefault().register(this);
	}
	
	

	private void getIntentData() {
		bid = getIntent().getStringExtra("bid");
		ownerId = getIntent().getStringExtra("ownerId");
		type = getIntent().getIntExtra("type", 2);
		position = getIntent().getIntExtra("position", 0);
	}

	private void setTop() {
		tvTitle.setText("申请维修表");
		if (type == 4) {
			tvSearch.setCompoundDrawables(null, null, null, null);
			tvSearch.setText("新增");
		}
		else {
			tvSearch.setVisibility(View.GONE);
		}
		
	}

	private void setAdapter() {
		mRepairItemAdapter = new RepairItemAdapter(this, mRepairItemParents,
				type);
		mainList.setGroupIndicator(null);// 这个是去掉父级的箭头
		mainList.setAdapter(mRepairItemAdapter);
		mainList.setOnChildClickListener(new OnChildClickListener() {

			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {
				return true;
			}
		});

	}

	private void getData() {
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN,
				UserInfoUtil.getCurrentUserAccessToken());
		params.put("bid", bid);

		dialog = showDialog(dialog);

		VolleyRequest.StringRequestPost(this,
				WebApi.MAINTENANCE_LEADER_REPAIR_VIEW_REPORT, "", params,
				new StringInterface(this) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								String data = obj.getString("data");
								List<RepairItemBean> temp = new Gson()
										.fromJson(
												data,
												new TypeToken<List<RepairItemBean>>() {
												}.getType());

								updateCopy = temp;
								// 保存到表头
								for (int i = 0; i < temp.size(); i++) {
									RepairItemParent parent = new RepairItemParent();
									parent.setTitle("维修报表" + (i + 1));
									List<RepairItemBean> childList = new ArrayList<RepairItemBean>();
									RepairItemBean child = temp.get(i);
									child.setOldRecord(child.getRecord());
									child.setOldEquipStatu(child.getEquip_status());
									child.setOldPrice(child.getPrice());
									child.setOldAmount(child.getAmount());
									child.setOldPayer(child.getPayer());
									child.setOldCheckStatu(child.getIs_check());
									childList.add(child);
									parent.setChildList(childList);
									mRepairItemParents.add(parent);
								}
								mRepairItemAdapter.putAllSp();
								mRepairItemAdapter.notifyDataSetChanged();
								checkPost();

							} else if (status.equals("404")
									&& info.contains("尚未登录")) {
								ToastUtil.getInstances().showMsg(
										"尚未登录或该用户在其他地方登录，请重新登录！");
								// 清除环信登录
								UserHelp.getInstance().clearUser(
										AppBase.Context, true);
								return;
							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
							hideDialog(dialog);
						}
					}

					@Override
					public void stringError(VolleyError error) {
						hideDialog(dialog);
						ToastUtil.getInstances().showMsg(
								R.string.err_http_response);
					}
				});
	}

	@OnClick({ R.id.tvBack,R.id.tvSearch,R.id.tvUpload })
	public void onClick(View view) {
		Intent intent = null;
		switch (view.getId()) {
		case R.id.tvBack:
			finish();
			break;
		case R.id.tvSearch:
			intent = new Intent(this,MaintenanceDeclareRepairTableActivity.class);
			intent.putExtra("ownerId", ownerId);
			intent.putExtra("bid", bid);
			startActivityForResult(intent, ADD);
			
			break;
		case R.id.tvUpload:
			if (type == 1 || type == 4) {
				if (isShowSkinConfirm()) {
					//待审核
					mConfirmPopView.showPopWindow();
				}
				else {
					//不需要审核
					doTempPost(1);
				}
			}
			else if(type == 3){
				doTempPost(0);
			}
			else if(type == 5){
				doOwnerCheckPost();
			}
			
			break;
		default:
			break;
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == ADD && resultCode == RESULT_OK) {
			RepairItemBean child = new Gson().fromJson(data.getStringExtra("bid_obj"), RepairItemBean.class);
			if (child == null) {
				return;
			}
			RepairItemParent parent = new RepairItemParent();
			parent.setTitle("维修报表" + (mRepairItemParents.size()+1)+"");
			List<RepairItemBean> childList = new ArrayList<RepairItemBean>();
			childList.add(child);
			parent.setChildList(childList);
			parent.setOwnerId(ownerId);
			mRepairItemParents.add(parent);
			mRepairItemAdapter.notifyDataSetChanged();
			checkPost();
		}
	}
	
	/**   
	 * @author: HYM 
	 * @Title: checkPost   
	 * @Description: TODO(检测是否显示申报)    void 
	 * @date: 2017-11-9
	 */  
	void checkPost()
	{
		if (mRepairItemParents.size()>0 && type == 4) {
			tvUpload.setVisibility(View.VISIBLE);
			tvUpload.setEnabled(true);
		}
		else if(type == 1){
			tvUpload.setVisibility(View.VISIBLE);
			if (isNull()) {
				tvUpload.setEnabled(false);
			}
			else {
				tvUpload.setEnabled(true);
			}
			
		}
		else if(type == 5){
			tvUpload.setVisibility(View.VISIBLE);
			tvUpload.setText("提交");
			if (isOwnerCheckAllDo()) {
				tvUpload.setEnabled(true);
			}
			else {
				tvUpload.setEnabled(false);
			}
		}
		else if (type == 3) {
			tvUpload.setVisibility(View.VISIBLE);
			if(isUpdate())
			{
				tvUpload.setEnabled(true);
			}
			else {
				tvUpload.setEnabled(false);
			}
		}
		else
		{
			tvUpload.setVisibility(View.GONE);
		}
	}
	
	void doTempPost(int auditor_status)
	{
		String url;
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN,
				UserInfoUtil.getCurrentUserAccessToken());
		params.put("bid", bid);
		params.put("auditor_status", auditor_status+"");

		if (type == 1 || type == 3) {
			url = WebApi.MAINTENANCE_REPAIR_DECLARE;
			List<RepairItemBean> temp = new ArrayList<RepairItemBean>();
			for (int i = 0; i < mRepairItemAdapter.getmList().size(); i++) {
				RepairItemParent repairItemParent = mRepairItemAdapter.getmList()
						.get(i);
				for (int j = 0; j < repairItemParent.getChildList().size(); j++) {
					RepairItemBean repairItemBean = repairItemParent.getChildList().get(j);
					//如果是重新申报流程，就重置掉当前的审核状态为待审核
					if (type == 3 && repairItemBean.getAuditor_status() == 2) {
						repairItemBean.setAuditor_status(0);
					}
					temp.add(repairItemBean);
				}
			}
			params.put("brd_data", new Gson().toJson(temp));
		}
		else {
			url = WebApi.MAINTENANCE_REPAIR_ALL_TEMP_FINISH;
		}
		Log.e(" params  ", params.toString());
		Log.e(" url  ", url);
		dialog = showDialog(dialog);

		VolleyRequest.StringRequestPost(this,
				url, "", params,
				new StringInterface(this) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								ToastUtil.getInstances().showMsg(info);
								EventBus.getDefault().post(new RepairTaskListEvent(type, position, 1));
								finish();
							} else if (status.equals("404")
									&& info.contains("尚未登录")) {
								ToastUtil.getInstances().showMsg(
										"尚未登录或该用户在其他地方登录，请重新登录！");
								// 清除环信登录
								UserHelp.getInstance().clearUser(
										AppBase.Context, true);
								return;
							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
							hideDialog(dialog);
						}
					}

					@Override
					public void stringError(VolleyError error) {
						hideDialog(dialog);
						ToastUtil.getInstances().showMsg(
								R.string.err_http_response);
					}
				});
	}
	
	
	/**   
	 * @author: HYM 
	 * @Title: doOwnerCheckPost   
	 * @Description: TODO(业主提交审核的动作)    void 
	 * @date: 2017-11-10
	 */  
	void doOwnerCheckPost()
	{
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN,
				UserInfoUtil.getCurrentUserAccessToken());
		params.put("bid", bid);
		
		List<RepairItemBean> temp = new ArrayList<RepairItemBean>();
		for (int i = 0; i < mRepairItemAdapter.getmList().size(); i++) {
			RepairItemParent repairItemParent = mRepairItemAdapter.getmList()
					.get(i);
			for (int j = 0; j < repairItemParent.getChildList().size(); j++) {
				RepairItemBean repairItemBean = repairItemParent.getChildList().get(j);
				temp.add(repairItemBean);
			}
		}
		params.put("brd_data", new Gson().toJson(temp));
		Log.e(" params  ", params.toString());
		dialog = showDialog(dialog);
		
		VolleyRequest.StringRequestPost(this,
				WebApi.OWNER_REPAIR_CHECK_SUBMIT, "", params,
				new StringInterface(this) {
			
			@Override
			public void stringSuccess(String result) {
				try {
					JSONObject obj = new JSONObject(result);
					String status = obj.getString("status");
					String info = obj.getString("info");
					if (status.equals("200")) {
						ToastUtil.getInstances().showMsg(info);
						EventBus.getDefault().post(new OwnerCheckEvent(position));
						finish();
					} else if (status.equals("404")
							&& info.contains("尚未登录")) {
						ToastUtil.getInstances().showMsg(
								"尚未登录或该用户在其他地方登录，请重新登录！");
						// 清除环信登录
						UserHelp.getInstance().clearUser(
								AppBase.Context, true);
						return;
					} else {
						ToastUtil.getInstances().showMsg(info);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				} finally {
					hideDialog(dialog);
				}
			}
			
			@Override
			public void stringError(VolleyError error) {
				hideDialog(dialog);
				ToastUtil.getInstances().showMsg(
						R.string.err_http_response);
			}
		});
	}

	@Override
	public void OnDeleteListener() {
		doTempPost(1);		
	}

	@Override
	public void OnCancleListener() {
		doTempPost(0);
	}

	/**   
	 * <p>Title: OnShowListener</p>   
	 * <p>Description: </p>      
	 * @see ConfirmPopInterface#OnShowListener()
	 */ 
	@Override
	public void OnShowListener() {
		// TODO Auto-generated method stub
		
	}

	/**   
	 * <p>Title: OnHideListener</p>   
	 * <p>Description: </p>      
	 * @see ConfirmPopInterface#OnHideListener()
	 */ 
	@Override
	public void OnHideListener() {
		// TODO Auto-generated method stub
		
	}
	
	
	/**   
	 * @author: HYM 
	 * @Title: isCheckAllDo   
	 * @Description: TODO(判断业主是否已经全部审核完成)   
	 * @return boolean 
	 * @date: 2017-11-10
	 */  
	boolean isOwnerCheckAllDo() {
		boolean isCheckAllDo = true;
		for (int i = 0; i < mRepairItemParents.size(); i++) {
			List<RepairItemBean> repairItemBeans = mRepairItemParents.get(i).getChildList();
			for (int j = 0; j < repairItemBeans.size(); j++) {
				if (repairItemBeans.get(j).getIs_check() == 0) {
					continue;
				}
				if (repairItemBeans.get(j).getAuditor_status() == 0) {
					isCheckAllDo = false;
					break;
				}
			}
			if (!isCheckAllDo) {
				break;
			}
		}
		return isCheckAllDo;
	}
	
	/**   
	 * @author: HYM 
	 * @Title: isShowSkinConfirm   
	 * @Description: TODO(判断新增或者编辑是否显示跳过业主审核的弹窗)   
	 * @return boolean 
	 * @date: 2017-11-10
	 */  
	boolean isShowSkinConfirm()
	{
		boolean isShowSkinConfirm = false;
		for (int i = 0; i < mRepairItemParents.size(); i++) {
			List<RepairItemBean> repairItemBeans = mRepairItemParents.get(i).getChildList();
			for (int j = 0; j < repairItemBeans.size(); j++) {
				if (repairItemBeans.get(j).getIs_check() == 1) {
					isShowSkinConfirm = true;
					break;
				}
			}
			if (isShowSkinConfirm) {
				break;
			}
		}
		return isShowSkinConfirm;
	}
	
	
	/**   
	 * @author: HYM 
	 * @Title: isUpdate   
	 * @Description: TODO(检测是否有更新数据)   
	 * @return boolean 
	 * @date: 2017-11-10
	 */  
	boolean isUpdate()
	{
		boolean isUpdate = false;
		for (int k = 0; k < updateCopy.size(); k++) {
			RepairItemBean temp = updateCopy.get(k);
			if (!temp.getOldRecord().equals(temp.getRecord())) {
				isUpdate = true;
				break;
			}
			if (temp.getEquip_status() != temp.getOldEquipStatu()) {
				isUpdate = true;
				break;
			}
			if (!temp.getOldPrice().equals(temp.getPrice())) {
				isUpdate = true;
				break;
			}
			if (!temp.getOldAmount().equals(temp.getAmount())) {
				isUpdate = true;
				break;
			}
			if (temp.getOldPayer() != temp.getPayer()) {
				isUpdate = true;
				break;
			}
			if (temp.getOldCheckStatu() != temp.getIs_check()) {
				isUpdate = true;
				break;
			}
			
			if (isUpdate) {
				break;
			}
		}
		
		return isUpdate;
		
	}
	
	boolean isNull()
	{
		boolean isNull = false;
		for (int k = 0; k < updateCopy.size(); k++) {
			RepairItemBean temp = updateCopy.get(k);
			if (TextUtils.isEmpty(temp.getBh_code())) {
				isNull = true;
				break;
			}
			if (TextUtils.isEmpty(temp.getPlace())) {
				isNull = true;
				break;
			}
			if (TextUtils.isEmpty(temp.getRecord())) {
				isNull = true;
				break;
			}
			if (TextUtils.isEmpty(temp.getPro_name())) {
				isNull = true;
				break;
			}
			if (TextUtils.isEmpty(temp.getProduct())) {
				isNull = true;
				break;
			}
			if (TextUtils.isEmpty(temp.getPro_date())) {
				isNull = true;
				break;
			}
			if (TextUtils.isEmpty(temp.getPro_safe_date())) {
				isNull = true;
				break;
			}
			if (TextUtils.isEmpty(temp.getPro_type())) {
				isNull = true;
				break;
			}
			if (TextUtils.isEmpty(temp.getPrice())) {
				isNull = true;
				break;
			}
			if (TextUtils.isEmpty(temp.getAmount())) {
				isNull = true;
				break;
			}
			
			
			if (isNull) {
				break;
			}
		}
		
		return isNull;
		
	}
}
